const path = require('path')
const marked = require('marked')
const {remote, ipcRenderer} = require('electron')
const {Menu} = remote
const mainProcess = remote.require('./main') // 用镜像引入主进程
const markdownView = document.querySelector('#markdown')
const htmlView = document.querySelector('#html')
const newFileButton = document.querySelector('#new-file')
const openFileButton = document.querySelector('#open-file')
const saveMarkdownButton = document.querySelector('#save-markdown')
const revertButton = document.querySelector('#revert')
const saveHtmlButton = document.querySelector('#save-html')
const showFileButton = document.querySelector('#show-file')
const openInDefaultButton = document.querySelector('#open-in-default')
let timer = null

const currentWindow = remote.getCurrentWindow()
let fullPath = null // 当前文件的路径
let originalContent = '' // 文件原始的内容
let currentContent = ''

const renderMarkdownToHtml = markdown => {
  htmlView.innerHTML = marked(markdown, { sanitize: true })
}

markdownView.addEventListener('keyup', (e) => {
  clearTimeout(timer)
  timer = setTimeout(() => {
    currentContent = e.target.value
    const boo = currentContent === ''
    saveHtmlButton.disabled = !currentContent
    renderMarkdownToHtml(currentContent)
    updateUserInterface(currentContent !== originalContent)
    // 给主进程发送数据，标记着当前有没有被修改
    mainProcess.ifEdited(currentContent !== originalContent, currentWindow)
  }, 1000)
})

openFileButton.addEventListener('click', () => {
  mainProcess.getFileFromUser(currentWindow)
})
ipcRenderer.on('file-opened', (e, file, content) => {
    // if (currentWindow.isDocumentEdited()) {
    if (true) {
      const result = remote.dialog.showMessageBoxSync(currentWindow, {
       type: 'warning',
       title: 'Overwrite Current Unsaved Changes?',
       message: 'Open a new file in this window will overwrite your unsaved changes, open this file anyway?',
       buttons: ['Yes', 'Cancel'],
       defaultId: 0,
       cancelId: 1
     })
     if (result === 1) {
       return
     }
     renderFile(file, content)
    }
  })
  ipcRenderer.on('update-fullPath', file => {
    fullPath = file // 更新当前文件路径
    console.log('update-fullPath', fullPath)
  })

  // 文件被外部程序修改时，提示用户
  ipcRenderer.on('file-changed', (e, file, content) => {
    const result = remote.dialog.showMessageBoxSync(currentWindow, {
      type: 'warning',
      title: 'Overwrite Current Unsaved Changes?',
      message: 'Another application has changed this file. Load changes?',
      buttons: ['Yes', 'Cancel'],
      defaultId: 0,
      cancelId: 1
    })
    if (result === 1) {
      return
    }
    renderFile(file, content)
  })
// 新建文件
newFileButton.addEventListener('click', () => {
  mainProcess.creatWindow()
})

// 修改窗口标题
function updateUserInterface(isEdited) {
  console.log('isEdited', isEdited)
  let title = 'Fire Sale'
  if (fullPath) {
    title = `${path.basename(fullPath)} - ${title}`
  }
  if (isEdited) {
    title = `${title} (Edited)`
    saveMarkdownButton.disabled = !isEdited
    revertButton.disabled = !isEdited
  }
  // windows
  currentWindow.setTitle(title)
  // macOS
  currentWindow.setDocumentEdited(isEdited)
}
saveHtmlButton.addEventListener('click', () => {
  mainProcess.saveHtml(currentWindow, htmlView.innerHTML)
})
saveMarkdownButton.addEventListener('click', () => {
  mainProcess.saveMarkdown(currentWindow, fullPath, markdownView.value)
})
// 回滚
revertButton.addEventListener('click', () => {
  markdownView.value = originalContent
  renderMarkdownToHtml(originalContent)
})

// 拖拽
document.addEventListener('dragstart', e => e.preventDefault())
document.addEventListener('dragover', e => e.preventDefault())
document.addEventListener('dragleave', e => e.preventDefault())
document.addEventListener('drop', e => e.preventDefault())
const getDraggedFile = e => {
  return e.dataTransfer.items[0]
}
const getDroppedFile = e => {
  return e.dataTransfer.files[0]
}
const fileTypeIsSupported = file => {
  // file.type 仅仅对常见文件类型可靠。例如图像、文档、音频和视频。不常见的文件扩展名会返回空字符串
  return ['text/plain'].includes(file.type)
}
markdownView.addEventListener('dragover', e => {
  const file = getDraggedFile(e)
  if (fileTypeIsSupported(file)) {
    markdownView.classList.add('drag-over')
  } else {
    markdownView.classList.add('drag-error')
  }
})

markdownView.addEventListener('dragleave', e => {
  markdownView.classList.remove('drag-over')
  markdownView.classList.remove('drag-error')
})

markdownView.addEventListener('contextmenu', e => {
  e.preventDefault()
  markdownContextMenu.popup()
  // alert('One day, a context menu will go here')
})
const markdownContextMenu = Menu.buildFromTemplate([
  {label: 'Open File', click() {mainProcess.getFileFromUser()}},
  {type: 'separator'},
  {label: 'Cut', role: 'cut'},
  {label: 'Copy', role: 'copy'},
  {label: 'Paste', role: 'paste'},
  {label: 'Select All', role: 'selectAll'}
])

markdownView.addEventListener('drop', e => {
  const file = getDroppedFile(e)
  if (fileTypeIsSupported(file)) {
    mainProcess.openFile(currentWindow, file.path)
  } else {
    alert('That file type is not supported')
  }
  markdownView.classList.remove('drag-over')
  markdownView.classList.remove('drag-error')

})


// // 重构显示新文件操作
const renderFile = (file, content) => {
  filePath = file
  originalContent = content

  markdownView.value = content
  renderMarkdownToHtml(content)
  updateUserInterface(false)
}

// 监听自定义菜单发出来的保存markdown和savehtml事件
ipcRenderer.on('save-markdown', () => {
  mainProcess.saveMarkdown(currentWindow, fullPath, markdownView.value)
})
ipcRenderer.on('save-html', () => {
  mainProcess.saveHtml(currentWindow, fullPath, htmlView.innerHTML)
})